package main

import (
	"fmt"
	"sync"
)

// Singleton 单例结构体
type Singleton struct {
	Data string
}

var (
	instance *Singleton //全局变量保存单例实例
	once     sync.Once  //确保GetInstance函数只会被执行一次，从而保证单例的唯一性
)

// GetInstance 获取Singleton实例的指针
func GetInstance() *Singleton {
	once.Do(func() {
		instance = &Singleton{
			Data: "singleton data",
		}
	})
	return instance
}

func main() {
	// 创建多个goroutine并发获取Singleton实例
	var wg sync.WaitGroup
	for i := 0; i < 10; i++ {
		wg.Add(1)
		go func() {
			defer wg.Done()
			singleton := GetInstance()
			fmt.Printf("Instance Data: %s,%d\n", singleton.Data, i)
		}()
	}
	wg.Wait()

	// 修改Singleton实例的数据
	singleton := GetInstance()
	singleton.Data = "Hello, Singleton!"
	fmt.Printf("Modified Instance Data: %s\n", singleton.Data)
}
